package com.vedana.bankmobile.dao.impl;

import java.util.ArrayList;
import java.util.List;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Transaction;
import com.vedana.bankmobile.dao.CustomerDao;
import com.vedana.bankmobile.shared.Customer;

/**
 * GAE Datastore DAO class for customers.
 * 
 * @author Didier MOISE
 *
 */
public class CustomerDatastoreDao implements CustomerDao {
	private DatastoreService datastore;

	/**
	 * Constructor
	 * 
	 * @param datastore Datastore Service.
	 */
	public CustomerDatastoreDao(DatastoreService datastore) {
		this.datastore = datastore;
	}

	@Override
	public void addCustomer(Customer customer) {
		Transaction tx = datastore.beginTransaction();

		Entity entity = customerToNewEntity(customer);

		datastore.put(tx, entity);
		tx.commit();
	}

	@Override
	public List<Customer> listCustomers(String userId) {
		ArrayList<Customer> result = new ArrayList<Customer>();
		
		Query query = new Query("Customer");
		PreparedQuery pq = datastore.prepare(query);

		for (Entity entity : pq.asIterable()) {
			Customer customer = entityToCustomer(entity);
			result.add(customer);
		}
		
		return result;
	}

	/**
	 * Convert GAE entity to customer object
	 * @param entity
	 * @return
	 */
	private Customer entityToCustomer(Entity entity) {
		Customer customer = new Customer();
		
		customer.setId(entity.getKey().getId());
		customer.setLabel((String)entity.getProperty("label"));
		
		return customer;
	}

	/**
	 * Convert customer object to new GAE entity
	 * @param customer
	 * @return
	 */
	private Entity customerToNewEntity(Customer customer) {
		Key key = KeyFactory.createKey("Customer", customer.getId());

		Entity entity = new Entity(key);
		entity.setProperty("label", customer.getLabel());
		
		return entity;
	}
}
